package com.haiwen.boot.controller.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.haiwen.boot.utils.RedisContext;
import com.haiwen.boot.utils.RedisUtil;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

/**
 * 对频繁请求进行处理
 */
@Component
@Log4j
public class FrequentInterception implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String blogID = request.getParameter("blogID");
        String userID = request.getParameter("userID");
        Date currentTime =new Date();
        if (!redisUtil.hasKey(RedisContext.BLOGID_KEY + blogID)) return true;
        Map<Object, Object> blogIdKey = redisUtil.hmget(RedisContext.BLOGID_KEY + blogID);
        if (!blogIdKey.containsKey(RedisContext.USERID_KEY + userID)) return true;
        Date LastCommentTime = (Date)blogIdKey.get(RedisContext.USERID_KEY + userID);
        if (currentTime.getTime() - LastCommentTime.getTime() > 7000) return  true;
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "200");
        jsonObject.put("message", "操作频繁，请稍后再试！");
        response.getWriter().write(JSONObject.toJSONString(jsonObject));
        response.getWriter().flush();
        out.flush();
        out.close();
        return false;
    }
}
